<?php

require_once 'version_fixes.php';

/*
 * Example: http://localhost:8081
 */
function current_root_url() {
 $url = 'http';
 if (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") {
 	$url .= "s";
 }
 $url .= "://".$_SERVER["SERVER_NAME"];
 if ($_SERVER["SERVER_PORT"] != "80") {
  $url .= ":".$_SERVER["SERVER_PORT"];
 }
 return $url;
}

/*
 * Example: http://localhost:8081/EclipsePHP/LanguageTandem/util.php
 */
function current_page_url() {
 return current_root_url().$_SERVER["SCRIPT_NAME"];
}

/*
 * Example: http://localhost:8081/EclipsePHP/LanguageTandem/util.php?value=true
 */
function current_request_url() {
 return current_root_url().$_SERVER["REQUEST_URI"];
}

function generate_random_string($length=20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters)-1)];
    }

    return $string;
}

function ends_with($haystack, $needle) {
    $length = strlen($needle);
    $start  = $length * -1; //negative
    return substr($haystack, $start) === $needle;
}

function starts_with($haystack, $needle) {
    return substr($haystack, 0, strlen($needle)) === $needle;
}

/**
* Inserts values from $arr2 after (or before) $key in $arr1
* if $key is not found, $arr2 is appended to $arr1 using array_merge()
*
* @param $arr1
*   array to insert into
* @param $key
*   key of $arr1 to insert after
* @param $arr2
*   array whose values should be inserted
* @param $before
*   insert before the given key. defaults to inserting after
* @return
*   merged array
*/
function array_insert($arr1, $key, $arr2, $before = FALSE){
  $done = FALSE;
  foreach($arr1 as $arr1_key => $arr1_val){
    if(!$before){
      $new_array[$arr1_key] = $arr1_val;
    }
    if($arr1_key === $key && !$done){
      foreach($arr2 as $arr2_key => $arr2_val){
        $new_array[$arr2_key] = $arr2_val;
      }
      $done = TRUE;
    }
    if($before){
      $new_array[$arr1_key] = $arr1_val;
    }
  }
  if(!$done){
    $new_array = array_merge($arr1, $arr2);
  }
  return $new_array;
}

function array_flatten($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    }
    else {
      $result[$key] = $value;
    }
  }
  return $result;
} 

function array_flatten_values_only($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten_values_only($value));
    }
    else {
      $result[] = $value;
    }
  }
  return $result;
} 

function all($array) {
	foreach ($array as $item) {
		if (!$item) {
			return false;
		}
	}
	return true;
}

function any($array) {
	foreach ($array as $item) {
		if ($item) {
			return true;
		}
	}
	return false;
}

function is_json($string) {
	json_decode($string);
	return json_last_error() === JSON_ERROR_NONE;
}

function r($arg) {
	return $arg;
}

function str_endsWith($haystack, $needle) {
    $length = strlen($needle);
    $start  = $length * -1; //negative
    return (substr($haystack, $start) === $needle);
}

function array_extract($array, $keys, $only_if_present=false) {
	$new = array();
	foreach ($keys as $key) {
		if (isset($array[$key]) or !$only_if_present) {
			$new[$key] = $array[$key];
			unset($array[$key]);
		}
	}
	return $new;
}

/**
 * Apply htmlentities on every value in an array.
 * 
 * @param array $request
 * @param array $skip keys to skip
 */
function htmlentities_array($request, $skip=array()) {
	$new = array();
	foreach ($request as $name => $value) {
		if (in_array($name, $skip)) {
			$new[$name] = $value;
		}
		else {
			$new[$name] = htmlentities($value, ENT_QUOTES);
		}
	}
	return $new;
}


// Untested
function remove_empty_lines($string) {
	// Remove empty lines
	$lines = explode('\n', $string);
	$filtered = array();
	foreach ($lines as $line) {
		$line = rtrim($line);
		if ($line !== '') {
			$filtered[] = $line;
		}
	}
	return implode('\n', $filtered);
}
		
		

function LT_mail($to, $subject, $message, $additional_headers=null) {
	if (DEBUG) {
		$now = date("Y-m-d H:i:s");
		log_message('debug_emails.txt', "
TO: $to
SUBJECT: $subject
DATE: $now
MESSAGE: 

$message
		");
	}
	else {
		try {
			return mail($to, $subject, $message, 
						"From: \"Tandem Delft website\" <no-reply@language.tudelft.nl>\n" . $additional_headers, 
						'-f no-reply@language.tudelft.nl');
		} catch (ErrorOrWarningException $e) {
			return false;
		}
	}
}

/**
 * Try to log a message, to a log file in the logs/ directory. Fails silently if writing to that file is not possible.
 * 
 * @param string $filename
 * @param string $message
 */
function log_message($filename, $message) {
	$filename = dirname($_SERVER['SCRIPT_FILENAME']) . '/logs/' . $filename;
	try {
		$dir = dirname($filename);
		if (!file_exists($dir)){
			mkdir($dir, 0777, true);
		}
		$handle = @fopen($filename, 'a');
	} catch (Exception $e) {
		$handle = false;
	}
	
	if ($handle !== false) {
		fwrite($handle, $message);
		fwrite($handle, '
-----------------------------------------------------
		');
		fclose($handle);
	}
}
?>